"""
    login应用工具包
"""
from .models import User
from django.contrib.auth.backends import ModelBackend
import re


def get_user_by_account(account):
    """
    通过账号获取用户
    :param account: 用户名或手机号或邮箱
    :return:
    """
    try:
        if re.match(
                r'^[1](([3][0-9])|([4][5-9])|([5][0-3,5-9])|([6][5,6])|([7][0-8])|([8][0-9])|([9][1,8,9]))[0-9]{8}$',
                account):
            # account是手机号
            user = User.objects.get(phone=account)
        elif re.match(r'^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$', account):
            # account是邮箱
            user = User.objects.get(email=account)
        else:
            # account是用户名
            user = User.objects.get(username=account)
    except User.DoesNotExist:
        return None
    else:
        return user


# 自定义用户认证后端
class UsernameAndPhoneBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        """
        重写用户认证方法
        :param request:
        :param username:用户名或手机号或邮箱
        :param password:密码明文
        :param kwargs:额外参数
        :return:user
        """
        # 使用账号查询用户
        user = get_user_by_account(username)
        print(user)
        # 如果可以查询到用户，需校验密码是否正确
        if user and user.check_password(password):
            return user
        else:
            return None
